/**
 * @author
 * @createtime
 * @class MaterialPurRealForm
 * @extends Ext.Window
 * @description MaterialPurReal表单
 */
MaterialPurRealForm = Ext.extend(Ext.Window, {
	//内嵌FormPanel
	formPanel : null,
	//构造函数
	constructor : function(_cfg) {
		Ext.applyIf(this, _cfg);
		//必须先初始化组件
		this.initUIComponents();
		MaterialPurRealForm.superclass.constructor.call(this, {
			id : 'MaterialPurRealFormWin',
			layout : 'fit',
			items : this.formPanel,
			modal : true,
			width : 850,
			height:490,
			maximizable : false,
			title : '[物资采购申请]详细信息',
			buttonAlign : 'center',
			buttons : this.buttons
		});
	},//end of the constructor
	//初始化组件
	initUIComponents : function() {
		var thizId = this.id;
		this.formPanel = new Ext.FormPanel({
			layout : 'form',
			trackResetOnLoad : true,
			bodyStyle : 'padding:10px 10px 10px 10px',
			border : false,
			url : __ctxPath + '/produce/saveMaterialPurReal.do',
			id : 'MaterialPurRealForm',
			defaults : {
				anchor : '98%,98%'
			},
			defaultType : 'textfield',
			items : [{
						name : 'materialPurReal.id',
						id : 'id',
						xtype : 'hidden',
						value : this.id == null ? '' : this.id
					},{
					xtype : 'container',
					layout : 'column',
					height : 25,
					defaults : {
						xtype : 'label',
						style : {
							margin : '0px 0px 3px 0px'
						}
					},
					items : [{
								text : '申请人：',
								width : 90
							}, {
								xtype : 'textfield',
								name : 'materialPurRealCreateUser',
								id : 'materialPurRealCreateUser',
								columnWidth : .5,
								readOnly:true,
								value:__currentUser
							}, {
								xtype : "hidden",
								name : "materialPurReal.createUser.userId",
								id : "materialPurReal.createUser.userId",
								value:__currentUserId
							}, {
								text : '申请时间：',
								style : 'margin-left:10px;',
								width : 60
							}, {
								xtype : 'datefield',
								name : 'materialPurReal.createTime',
								id : 'createTime',
								allowBlank : false,
								columnWidth : .4,
								format : 'Y-m-d',
								value:new Date()
							}]
				},{
					xtype : 'container',
					layout : 'column',
					height : 25,
					defaults : {
						xtype : 'label',
						style : {
							margin : '0px 0px 3px 0px'
						}
					},
					items : [{
								text : '物资采购计划：',
								width : 90
							}, {
								xtype : 'textfield',
								name : 'materialPurRealPurchaseName',
								id : 'materialPurRealPurchaseName',
								columnWidth : .91,
								readOnly:true,
								allowBlank:false,
								emptyText:'请选择物资采购计划',
								listeners:{
								      focus:function(){
												MaterialPurchaseSelector.getView(function(materialPurchaseId, proName, proId,planNo,planDate,quality) {
														Ext.getCmp("materialPurReal.project.id").setValue(proId);
														Ext.getCmp("materialPurRealProName").setValue(proName);
														Ext.getCmp("materialPurReal.materialPurchase.id").setValue(materialPurchaseId);
														Ext.getCmp("planNo").setValue(planNo);
														Ext.getCmp("quality").setValue(quality);
														if(!Ext.isEmpty(materialPurchaseId)){
															Ext.getCmp("materialPurRealPurchaseName").setValue('计划单号为：'+planNo+'的采购计划');
															Ext.getCmp("materialPurReal.resultGridDataGrid").getStore().load({
																params:{
																	start :0,
																	limit : 9999,
																	'Q_purchasePlan.id_L_EQ':materialPurchaseId
																}
															});
														}else{
															Ext.getCmp("materialPurRealPurchaseName").setValue('');
														}
													}, true).show();								      
								      }
								}
							}, {
								xtype : "hidden",
								name : "materialPurReal.materialPurchase.id",
								id : "materialPurReal.materialPurchase.id"
							}]
				},{
					xtype:'fieldset',
					title:'物资采购计划详情',
					items:[
					{
					xtype : 'container',
					layout : 'column',
					height : 25,
					defaults : {
						xtype : 'label',
						style : {
							margin : '0px 0px 3px 0px'
						}
					},
					items : [{
								text : '项目名称：',
								width : 90
							}, {
								xtype : 'textfield',
								name : 'materialPurRealProName',
								id : 'materialPurRealProName',
								columnWidth : .91,
								allowBlank : false,
								emptyText : '请选择项目',
								listeners : {
									'focus' : function() {
										ProjectSelector.getView(function(proId, proName, proNo) {
											Ext.getCmp("materialPurReal.project.id").setValue(proId);
											Ext.getCmp("materialPurRealProName").setValue(proName);
										}, true).show();
									}
								}
							}, {
								xtype : "hidden",
								name : "materialPurReal.project.id",
								id : "materialPurReal.project.id"
							}
							]
				}, {
					xtype : 'container',
					layout : 'column',
					height : 25,
					defaults : {
						xtype : 'label',
						style : {
							margin : '0px 0px 3px 0px'
						}
					},
					items : [{
								text : '计划单号：',
								width : 90
							}, {
								xtype : 'textfield',
								name : 'materialPurReal.planNo',
								id : 'planNo',
								columnWidth : .5,
								allowBlank : false,
								maxLength : 64
							}, {
								text : '质量要求：',
								style : 'margin-left:10px;',
								width : 60
							}, {
								xtype : 'textfield',
								name : 'materialPurReal.quality',
								id : 'quality',
								allowBlank : false,
								columnWidth : .4,
								maxLength : 64
							}]
				}, {
					xtype : 'container',
					layout : 'column',
					height : 25,
					defaults : {
						xtype : 'label',
						style : {
							margin : '0px 0px 3px 0px'
						}
					},
					items : [{
								text : '采购详情：',
								width:90
							}, {
								style : 'color:red',
								id : 'materialPurRealErrorLabel',
								text : '(*必填)'
							}]
				}, {
					xtype : 'container',
					style : 'padding-left:0px;margin-bottom:10px',
					layout : 'column',
					items : [{
								name : 'resultGridData',
								xtype : 'hidden',
								id : 'materialPurReal.resultGridData'
							}, {
								name : 'dataList',
								xtype : 'hidden',
								id : 'materialPurReal.dataList'
							}, {
								xtype : 'grid',
								id : 'materialPurReal.resultGridDataGrid',
								height : 220,
								width : '98%',
								stripeRows : true,
								trackMouseOver : true,
								clicksToEdit : 1,
								plugins : [new Ext.ux.grid.RowEditor({
									saveText : '保存',
									cancelText : '取消',
									errorText : '请输入完整信息',
									errorSummary : false
								})],
								store : new Ext.data.JsonStore({
									url : __ctxPath + '/produce/listMaterialPurRealInfo.do',
									root : 'result',
									totalProperty : 'totalCounts',
									remoteSort : true,
									fields : ['id', {
												name : 'materialId',
												mapping : 'material.id'
											}, {
												name : 'materialName',
												mapping : 'material.materialName'
											},'details', 'num', 'enterDate', 'position', 'requirement', 'remark','addOrMinus','changeNum'],
									listeners : {
										'update' : function(value) {
											var r = this.getRange();
											var resultArray = [];
											var jsonArr = [];
											var sum = 0;
											var rlen = r.length;
											for (var i = 0; i < rlen; i++) {
												resultArray.push([]);
												if (r[i].fields) {
													var fields = r[i].fields;
													var flen = fields.length;
													var obj = {
														id : null,
														material : {
															id : ''
														},
														details:'',
														num : '',
														enterDate : '',
														position : '',
														requirement : '',
														remark : '',
														addOrMinus:'',
														changeNum:0
													}
													for (var z = 0; z < flen; z++) {
														var fieldValue = r[i].get(fields.keys[z]);
//														if (Ext.isEmpty(fieldValue) || fieldValue == '请双击选择' || fieldValue == '请双击填写') {
//															continue;
//														}
														if (fields.keys[z] == 'id') {
															resultArray[i].push('ID:' + '');
															obj.id = null;
														} else if (fields.keys[z] == 'materialId') {
															resultArray[i].push('物资ID:' + fieldValue);
															obj.material.id = fieldValue;
														} else if (fields.keys[z] == 'details') {
															resultArray[i].push('详细说明:' + fieldValue);
															obj.details = fieldValue;
														} else if (fields.keys[z] == 'num') {
															resultArray[i].push('数量:' + fieldValue);
															obj.num = fieldValue;
														} else if (fields.keys[z] == 'materialName') {
															resultArray[i].push('物资名称:' + fieldValue);
														} else if (fields.keys[z] == 'enterDate') {
															resultArray[i].push('拟到场时间:' + FormatGMTtoLocal(fieldValue, "yyyy-MM-dd"));
															obj.enterDate = FormatGMTtoLocal(fieldValue, "yyyy-MM-dd");
														} else if (fields.keys[z] == 'position') {
															resultArray[i].push('施工（种植）位置:' + fieldValue);
															obj.position = fieldValue;
														} else if (fields.keys[z] == 'requirement') {
															resultArray[i].push('包装要求:' + fieldValue);
															obj.requirement = fieldValue;
														} else if (fields.keys[z] == 'remark') {
															resultArray[i].push('备注:' + fieldValue);
															obj.remark = fieldValue;
														} else if (fields.keys[z] == 'addOrMinus') {
															resultArray[i].push('改变类型:' + fieldValue);
															obj.addOrMinus = fieldValue;
														} else if (fields.keys[z] == 'changeNum') {
															resultArray[i].push('改变数量:' + fieldValue+";");
															obj.changeNum = fieldValue;
														}
													}
													jsonArr.push(obj);
												}
											}
											//删除空元素
											for (var i = 0; i < resultArray.length; i++) {
												if (resultArray[i].length == 0) {
													resultArray.splice(i, 1);
													i--;
												}
											}
											Ext.getCmp('materialPurReal.resultGridData').setValue(resultArray);
											Ext.getCmp('materialPurReal.dataList').setValue(Ext.util.JSON.encode(jsonArr));
										}
									}
								}),
								cm : new Ext.grid.ColumnModel({
									columns : [new Ext.grid.RowNumberer(), {
												dataIndex : 'id',
												width : 50,
												hidden : true
											}, {
												dataIndex : 'materialId',
												hidden:true,
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													id : 'materialPurReal.materialId',
													maxLength : 64
												}))
											}, {
												header : '物资名称',
												dataIndex : 'materialName',
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													allowBlank : false,
													id : 'materialPurReal.materialName',
													maxLength : 64,
													allowBlank : false,
													readOnly : true,
													emptyText : '请选择物资',
													listeners : {
														'focus' : function() {
															MaterialSelector.getView(function(materialIds, materialNos, materialNames) {
																Ext.getCmp("materialPurReal.materialId").setValue(materialIds);
																Ext.getCmp("materialPurReal.materialName").setValue(materialNames);
															}, true).show();
														}
													}
												}))
											}, {
												header : '详细说明',
												dataIndex : 'details',
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													allowBlank : false,
													maxLength : 64
												}))
											}, {
												header : '数量',
												dataIndex : 'num',
												editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
													allowBlank : false,
													maxLength : 9
												}))
											}, {
												header : '拟到场时间',
												dataIndex : 'enterDate',
												editor : new Ext.grid.GridEditor(new Ext.form.DateField({
													allowBlank : false,
													format : 'Y-m-d'
												})),
												renderer : function(value) {
													if (value == '') {
														return '';
													} else if (typeof value == "string") {
														return value;
													} else {
														return formatDate(value, 'yyyy-MM-dd');
													}
												}
											}, {
												header : '施工（种植）位置',
												dataIndex : 'position',
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													allowBlank : false,
													maxLength : 64
												}))
											}, {
												header : '包装要求',
												dataIndex : 'requirement',
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													allowBlank : false
												})),
												width : 150
											}, {
												header : '备注',
												dataIndex : 'remark',
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
												})),
												width : 150
											}, {
												header : '改变类型',
												dataIndex : 'addOrMinus',
												editor : new Ext.grid.GridEditor(new Ext.form.ComboBox({
													allowBlank : false,
													triggerAction:'all',
													mode:'local',
													store:['增加','减少'],
													maxLength : 64
												}))
											}, {
												header : '改变数量',
												dataIndex : 'changeNum',
												editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
													allowBlank : false,
													maxLength : 9
												}))
											}],
									defaults : {
										sortable : false,
										menuDisabled : false,
										width : 100
									}
								}),
								tbar : new Ext.Toolbar({
									height : 30,
									items : [{
												iconCls : 'btn-add',
												text : '添加',
												xtype : 'button',
												handler : function() {
													var DataRecord = Ext.data.Record.create([{
																name : 'id'
															}, {
																name : 'materialId'
															}, {
																name : 'materialName'
															}, {
																name : 'details'
															}, {
																name : 'num'
															}, {
																name : 'enterDate'
															}, {
																name : 'position'
															}, {
																name : 'requirement'
															}, {
																name : 'remark'
															}, {
																name : 'addOrMinus'
															}, {
																name : 'changeNum'
															}]);
													var store = Ext.getCmp('materialPurReal.resultGridDataGrid').store;
													var grid = Ext.getCmp('materialPurReal.resultGridDataGrid');

													var n1 = '';
													var n2 = 0;

													var newRowData = {
														materialId : n1,
														materialName : n1,
														details:n1,
														num : n1,
														enterDate : n1,
														position : n1,
														requirement : n1,
														remark : n1,
														addOrMinus:n1,
														changeNum:n1
													};
													var newRecord = new DataRecord(newRowData);
													store.add([newRecord]);

													grid.getSelectionModel().on('selectionchange', function(sm) {
														Ext.getCmp('materialPurReal.removeBtn').setDisabled(sm.getCount() < 1);
													});
												}
											}, {
												iconCls : 'btn-del',
												text : '删除',
												id : 'materialPurReal.removeBtn',
												xtype : 'button',
												handler : function() {
													var store = Ext.getCmp('materialPurReal.resultGridDataGrid').store;
													var grid = Ext.getCmp('materialPurReal.resultGridDataGrid');
													var s = grid.getSelectionModel().getSelections();
													for (var i = 0, r; r = s[i]; i++) {
														store.remove(r);
													}
													store.fireEvent("update");//更新事件
												}
											}]
								})
							}]
				}, {
					xtype : 'textfield',
					hidden : true,
					validator : function() {
						var resultGridData = Ext.getCmp('materialPurReal.resultGridData').getValue();
						var errorLabel = Ext.getCmp("materialPurRealErrorLabel");
						if (Ext.isEmpty(thizId)) {
							if (Ext.isEmpty(resultGridData)) {//为空显示提示
								errorLabel.setText('请填写采购详情');
								return false;
							}
						}
						return true
					}
				}
				]}
			]
		});
		//加载表单对应的数据	
		this.initData();
		//初始化功能按钮
		this.buttons = [
//				{
//					text : '保存',
//					iconCls : 'btn-save',
//					handler : this.save.createCallback(this.formPanel, this)
//				}, {
//					text : '重置',
//					iconCls : 'btn-reset',
//					handler : this.reset.createCallback(this.formPanel)
//				},
				{
					text : '关闭',
					iconCls : 'btn-cancel',
					handler : this.cancel.createCallback(this)
				}];
	},//end of the initcomponents
	/**
	 * 初始化数据
	 * 
	 * @param {}
	 *            formPanel
	 */
	initData : function() {
		//加载表单对应的数据	
		if (this.id != null && this.id != 'undefined') {
			Ext.getCmp('materialPurReal.resultGridDataGrid').getStore().load({params:{
					'Q_materialPurReal.id_L_EQ':this.id,
					start:0,
					limit:9999
			}});
			this.formPanel.getForm().load({
				deferredRender : false,
				url : __ctxPath + '/produce/getMaterialPurReal.do?id=' + this.id,
				waitMsg : '正在载入数据...',
				success : function(form, action) {
					var jsonData = Ext.util.JSON.decode(action.response.responseText);
					var res = jsonData.data;
					if (!Ext.isEmpty(res.project)) {
						Ext.getCmp("materialPurRealProName").setValue(res.project.proName);
						Ext.getCmp("materialPurRealProName").originalValue = res.project.proName;
						Ext.getCmp("materialPurReal.project.id").setValue(res.project.id);
						Ext.getCmp("materialPurReal.project.id").originalValue = res.project.id;
					}
					if (!Ext.isEmpty(res.materialPurchase)) {
						Ext.getCmp("materialPurRealPurchaseName").setValue('计划单号为：'+res.planNo+'的采购计划');
						Ext.getCmp("materialPurRealPurchaseName").originalValue = '计划单号为：'+res.planNo+'的采购计划';
						Ext.getCmp("materialPurReal.materialPurchase.id").setValue(res.materialPurchase.id);
						Ext.getCmp("materialPurReal.materialPurchase.id").originalValue = res.materialPurchase.id;
					}
					//Ext.getCmp("").originalValue=
				},
				failure : function(form, action) {
				}
			});
		}
	},
	/**
	 * 重置
	 * 
	 * @param {}
	 *            formPanel
	 */
	reset : function(formPanel) {
		formPanel.getForm().reset();
	},
	/**
	 * 取消
	 * 
	 * @param {}
	 *            window
	 */
	cancel : function(window) {
		window.close();
	},
	/**
	 * 保存记录
	 */
	save : function(formPanel, window) {
		if (formPanel.getForm().isValid()) {
			formPanel.getForm().submit({
				method : 'POST',
				waitMsg : '正在提交数据...',
				success : function(fp, action) {
					Ext.ux.Toast.msg('操作信息', '成功保存信息！');
					var gridPanel = Ext.getCmp('MaterialPurRealGrid');
					if (gridPanel != null) {
						gridPanel.getStore().reload();
					}
					window.close();
				},
				failure : function(fp, action) {
					Ext.MessageBox.show({
						title : '操作信息',
						msg : '信息保存出错，请联系管理员！',
						buttons : Ext.MessageBox.OK,
						icon : Ext.MessageBox.ERROR
					});
					//window.close();
				}
			});
		}
	}//end of save

});